<template>
    <div id="app">
      <div class="chat-container">
        <div class="chat-show">
            <!-- 显示消息列表 -->
            <ul class="messages">
              <li v-for="message in messages" :key="message.id" :class="{ 'message-sent': message.user === currentUser }">
                  <div class="avatar" :style="{ backgroundImage: `url(${message.avatar})` }"></div>
                  <div class="message-content">
                  <strong>{{ message.user }}</strong>
                  <p>{{ message.text }}</p>
                  <span>{{ message.time }}</span>
                  </div>
              </li>
            </ul>
            <div v-show="answer!=''">
              <div class="avatar" :style="{ backgroundImage: `url(${answerMessage.avatar})` }"></div>
              <div class="message-content">
              <strong>{{ answerMessage.user }}</strong>
              <p>{{ answer }}</p>
              <span>{{ answerMessage.time }}</span>
              </div>
            </div>
        </div>
  
        <!-- 发送新消息的表单 -->
        <div>
            <input style="width: 1000px;" type="text" v-model="newMessage" placeholder="Type your message...">
            <button @click="sendMessage">发送</button>
            <button @click="sendStreamMessage">{{ buttonvalue }}</button>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import axios from '@/http'; // 导入你创建的 Axios 实例
  export default {
    data() {
      return {
        // 当前用户的名称
        currentUser: 'You',
        // 消息列表
        messages: [
        ],
        answerMessage: {},
        // 新消息输入框的内容
        newMessage: '你是谁',    
        answer:'',
        buttonvalue:'流发送'
      };
    },
    methods: {
      sendMessage() {
        if (this.newMessage.trim()) {
            //调用 接口，把name,age
            let question = { prompt: this.newMessage,top_p: 0.9,temperature: 0.9,top_k: 10}
            axios.post('/newchat',question).then(res=>{
              if (res){                
                console.log(res)                
                const now = new Date();
                const formattedTime = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                // 用户问题
                const newMsg = {
                  id: this.messages.length + 1,
                  user: this.currentUser,
                  avatar: 'https://via.placeholder.com/50x50/3333ff/ffffff', // 假设这是当前用户的头像
                  text: this.newMessage.trim(),
                  time: formattedTime
                };
                this.messages.push(newMsg);

                // 返回的答案
                const answer = {
                  id: this.messages.length + 1,
                  user: 'Alice',
                  avatar: 'https://via.placeholder.com/50x50', // 假设这是当前用户的头像
                  text: res.message,
                  time: formattedTime
                };
                this.messages.push(answer);

                this.newMessage = ''; // 清空输入框

              }
              else{
                console.log('发送失败')
              }
            })
        }
      },
      sendStreamMessage() {
        if (this.buttonvalue == '停止'){
          this.disconnectStream()
        }else{          
          if (this.answer!=''){
            this.messages.push(this.answerMessage);
            this.answer='';
            console.info(this.answerMessage)
          }
          this.buttonvalue = '停止'
          const now = new Date();
          const formattedTime = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
          // 用户问题
          const newMsg = {
            id: this.messages.length + 1,
            user: this.currentUser,
            avatar: 'https://via.placeholder.com/50x50/3333ff/ffffff', // 假设这是当前用户的头像
            text: this.newMessage.trim(),
            time: formattedTime
          };
          this.messages.push(newMsg);

          // 返回的答案
          this.answerMessage = {
            id: this.messages.length + 1,
            user: 'Alice',
            avatar: 'https://via.placeholder.com/50x50', // 假设这是当前用户的头像
            text: this.answer.slice(),
            time: formattedTime
          };
        
          this.source = new EventSource("http://localhost:8000/api/sse_notifications?prompt="+this.newMessage);

          this.source.onmessage = (event=> {
            if (event.data)
              this.answer = this.answer + event.data
            // this.answerMessage.text = this.answerMessage.text + event.data
            else{
              this.source.close();
              this.source = null;
              this.buttonvalue='流发送'
            }
          });
          this.source.onerror = (error=> {
              console.error('EventSource failed:', error);
              this.source.close();
              this.source = null;
          });

        }
      },
      disconnectStream() {
        this.buttonvalue='流发送'
        if (this.source) {
          this.source.close();
          this.source = null;
        }
      },
    }
  };
  </script>
  
  <style scoped>
  .chat-container {
    width: 1200px;
    height: 800px;
    margin: auto;
    padding: 20px;
    border: 1px solid #ccc;
    background-color: #f9f9f9;
    overflow-y: scroll;
  }
  .chat-show {
    height: 750px;
  }
  
  .messages {
    list-style-type: none;
    padding: 0;
  }
  
  .messages li {
    display: flex;
    align-items: flex-start;
    margin-bottom: 10px;
  }
  
  .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-size: cover;
    background-position: center;
    margin-right: 10px;
  }
  
  .message-content {
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    max-width: 80%;
    word-wrap: break-word;
    position: relative;
  }
  
  .message-sent .message-content {
    margin-left: auto;
    background-color: #007BFF;
    color: white;
  }
  
  .message-sent .avatar {
    margin-right: 0;
    margin-left: 10px;
  }
  
  .message-content::before {
    content: "";
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    border-style: solid;
    border-width: 8px 8px 8px 0;
    border-color: transparent #fff transparent transparent;
  }
  
  .message-sent .message-content::before {
    right: 100%;
    border-width: 8px 0 8px 8px;
    border-color: transparent transparent transparent #007BFF;
  }
  
  .message-content strong {
    display: block;
    margin-bottom: 5px;
  }
  
  .messages span {
    font-size: smaller;
    color: #888;
    display: block;
    margin-top: 5px;
  }
  </style>